package com.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.app.common.SystemConstant;
import com.app.conf.RedisService;
import com.app.model.UserModel;
import com.app.service.UserService;
import com.app.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Controller
@RestController
@RequestMapping("/QR")
public class QRCodeController {

    @Autowired
    UserService userService;

    @Autowired
    private RedisService redisService;
    @RequestMapping("/getCode")
    public Result<Object> createQRCode(HttpServletResponse response, HttpServletRequest request,String realName,String idCard) throws Exception {
        OutputStream stream = null;
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String mobile = TokenUtils.verify(token);
        UserModel user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405, "用户不存在");

        }
            //获取AccessToken
            String accessToken = WxQrCode.redisToken();
            //二维码携带参数 不超过32位 参数类型必须是字符串
            String userKey = getRandomString2(8);
            JSONObject json = new JSONObject();
            json.put("realName",realName);
            json.put("idCard",idCard);
            json.put("userKey",userKey);
            json.put("token",token);
            redisService.setStringKey(userKey,json);
            redisService.setExpire(userKey,30L,TimeUnit.MINUTES);
            WxQrCode.generateQrCode(""+ SystemConstant.DEFAULT_PDF_URL+"/qrcode/"+userKey+".png", "page_other/auth/authentication", "userKey="+userKey+"", accessToken);
            String tarImgPath=""+SystemConstant.DEFAULT_UPLOAD_SERVICE_URL+"qrcode/"+userKey+".png";   //目标图片的地址
            String img = Base64Util.getImageBase(tarImgPath);


        return Result.success(img);
    }

    @GetMapping("/getUserKeyInfo")
    public Result<Object> getUserKeyInfo(HttpServletRequest request,String userKey) throws Exception {
        //获取AccessToken
        JSONObject json = (JSONObject) redisService.getStringKey(userKey);
        return Result.success(json);
    }




    /**
     * 获取ACCESS_TOKEN
     * 官方文档地址:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html
     * <p>
     * 需要正确的 appid  和 secret  查看自己的微信开放平台
     */


    public static String getRandomString2(int length){
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<length;i++){
            int number=random.nextInt(3);
            long result=0;
            switch(number){
                case 0:
                    result=Math.round(Math.random()*25+65);
                    sb.append(String.valueOf((char)result));
                    break;
                case 1:
                    result=Math.round(Math.random()*25+97);
                    sb.append(String.valueOf((char)result));
                    break;
                case 2:
                    sb.append(String.valueOf(new Random().nextInt(10)));
                    break;
            }


        }
        return sb.toString();
    }

}
